import json

from django_redis import get_redis_connection

from meiduo_mall.utils.cookiesecret import CookieSecret


def  merge_cart_cookie_to_redis(request, response):

    # 获取cookie中的购物车数据
    cookie_str = request.COOKIES.get('carts')

    # 链接redis数据库对象
    client = get_redis_connection('carts')

    # 判断cookie中是否有数据
    if cookie_str is not None:
        # 解密
        cookie_dict = CookieSecret.loads(cookie_str)
        # 覆盖redis数据
        for sku_id in cookie_dict:
            client.hset(request.user.id, sku_id, json.dumps(cookie_dict[sku_id]))

        # 删除cookie
        response.delete_cookie('carts')
